#include "ph.h"

#define SensorPin 0         // pH meter Analog output to Arduino Analog Input 0
#define Offset -1.24         // deviation compensate
unsigned long int avgValue; // Store the average value of the sensor feedback
#ifdef ENABLE_PH

void setup()
{
    Serial.begin(9600);
    Serial.println("Ready"); // Test the serial monitor
}
void loop()
{
read_ph();
}

#endif
void phInit()
{
    pinMode(PH_PIN_DIRTY, INPUT);
    pinMode(PH_PIN_CLEAR, INPUT);
}

void read_ph(float *ph_dirty, float *ph_clear)
{
    int buf[10];                 // buffer for read analog
    float phValue;
    for (int i = 0; i < 10; i++) // Get 10 sample value from the sensor for smooth the value
    {
        buf[i] = analogRead(PH_PIN_DIRTY);
        delay(10);
    }
    for (int i = 0; i < 9; i++) // sort the analog from small to large
    {
        for (int j = i + 1; j < 10; j++)
        {
            if (buf[i] > buf[j])
            {
                int temp = buf[i];
                buf[i] = buf[j];
                buf[j] = temp;
            }
        }
    }
    avgValue = 0;
    for (int i = 2; i < 8; i++) // take the average value of 6 center sample
        avgValue += buf[i];
    phValue = (float)avgValue * 5.0 / 4095 / 6; // convert the analog into millivolt
    phValue = 3.5 * phValue + Offset;                 // convert the millivolt into pH value
    *ph_dirty = 14-phValue;



        for (int i = 0; i < 10; i++) // Get 10 sample value from the sensor for smooth the value
    {
        buf[i] = analogRead(PH_PIN_CLEAR);
        delay(10);
    }
    for (int i = 0; i < 9; i++) // sort the analog from small to large
    {
        for (int j = i + 1; j < 10; j++)
        {
            if (buf[i] > buf[j])
            {
                int temp = buf[i];
                buf[i] = buf[j];
                buf[j] = temp;
            }
        }
    }
    avgValue = 0;
    for (int i = 2; i < 8; i++) // take the average value of 6 center sample
        avgValue += buf[i];
    phValue = (float)avgValue * 5.0 / 4095 / 6; // convert the analog into millivolt
    phValue = 3.5 * phValue + Offset;                 // convert the millivolt into pH value
    *ph_clear = 14-phValue;
}